package cool.mtc.security.auth.custom;

import cool.mtc.security.SecurityProperties;
import cool.mtc.security.auth.AuthFormSupport;
import cool.mtc.security.constant.AuthConstant;
import cool.mtc.security.constant.SecurityConstant;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 明河
 */
public class CustomAuthFilter extends AbstractAuthenticationProcessingFilter {

    public CustomAuthFilter(SecurityProperties securityProperties) {
        super(new AntPathRequestMatcher(securityProperties.getAuthCustom().getAntPattern(), HttpMethod.POST.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        CustomAuthFormSupport formSupport = AuthFormSupport.transForm(request, CustomAuthFormSupport.class);
        request.setAttribute(SecurityConstant.REQUEST_ATTRIBUTE_KEY_AUTH_FORM, formSupport);
        request.setAttribute(SecurityConstant.REQUEST_ATTRIBUTE_KEY_AUTH_WAY, AuthConstant.AUTH_WAY_CUSTOM);
        CustomAuthToken token = new CustomAuthToken(formSupport);
        return super.getAuthenticationManager().authenticate(token);
    }
}
